package com.example.supplychainbackend.tool;

import com.example.supplychainbackend.controller.dto.user.UserSigDto;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.context.annotation.Configuration;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class JwtUtil {
    private static final SecretKey SECRET_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS256);
    private static final long EXPIRATION_MS = 36000000; // 1小时过期

    // 生成token
    public static String generateToken(String username, String userId, String eName, String eId) {
        Map<String, Object> claims = new HashMap<>();

        // 标准声明
        claims.put("sub", username);          // 主题（用户ID）
        claims.put("iat", new Date(System.currentTimeMillis()));            // 签发时间
        claims.put("exp", new Date(System.currentTimeMillis() + EXPIRATION_MS)); // 过期时间

        claims.put("enterpriseName", eName);
        claims.put("userId", userId);
        claims.put("enterpriseId", eId);

        return Jwts.builder()
//                .setSubject(username)
//                .setIssuedAt(new Date())
//                .setExpiration(expirationDate)
                .setClaims(claims)
                .signWith(SECRET_KEY)
                .compact();
    }

    // 验证token
    public static boolean validateToken(String token) {
        try {
            Jwts.parserBuilder()
                    .setSigningKey(SECRET_KEY)
                    .build()
                    .parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            System.out.println("TOKEN EXPIRED");
            return false;
        }
    }

    public static String getUsernameFromToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(SECRET_KEY)
                .build()
                .parseClaimsJws(token)
                .getBody()
                .getSubject();
    }

    public static UserSigDto getUserSignatureFromToken(String token) {
        Claims claims = Jwts.parserBuilder()
                .setSigningKey(SECRET_KEY)
                .build()
                .parseClaimsJws(token)
                .getBody();

        if ("0".equals(claims.get("enterpriseId", String.class)))
            throw new RuntimeException("用户未设置归属企业/机构，不可操作");

        return UserSigDto.builder().userName(claims.getSubject()).userId(claims.get("userId",String.class))
                .enterpriseName(claims.get("enterpriseName",String.class))
                .enterpriseId(claims.get("enterpriseId",String.class)).build();
    }

}
